package org.vectrics.recruiter.struts;

import org.apache.log4j.Category;
import org.vectrics.SystemException;
import org.vectrics.domain.Domain;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.mail.MailMessage;
import org.vectrics.mail.UserMailer;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.config.RecruitConfig;
import org.vectrics.user.PasswordEncryptor;
import org.vectrics.user.PasswordHintQuestion;
import org.vectrics.user.Person;
import org.vectrics.user.PersonService;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.struts.VectricsActionData;

/**
 * Struts action to email password to user who forgot password.
 * @author Mike Moore
 */
public class EmailPasswordAction extends VectricsStrutsAction {
    private transient Category log = Category.getInstance(this.getClass());
    private PersonService userManager = CoreServiceLocator.getPersonService();
    
    /**
     * execute the action
     */
	public String doExecute(VectricsActionData actionData) {
		String forward = "success";
		if (actionData.wasButtonPressed("cancel")) {
			forward = "cancel";
		} else {
			EmailPasswordForm form = (EmailPasswordForm)actionData.getForm();
			if (form == null) {
				form = new EmailPasswordForm();
				actionData.setRequestForm(form);
			}
					
			log.debug("execute() called, reading http parameters");
			String email = form.getEmailAddress();
			
			if (actionData.wasButtonPressed("submit.email.address")) {
				if (RecruitConfig.getRecruitInstance().getAnswerQuestionForEmailPassword(ThreadProperties.getDomain())) {
					log.info("System options required hint answer to receive password via email");
					PasswordHintQuestion question = CoreServiceLocator.getPersonService().findQuestionForEmailPassword(ThreadProperties.getDomain(), email);
					if (question == null) {
						forward = "no.hint.question.for.user";
					} else {
						form.setQuestion(question.getText());
						forward = "need.quest.answer";
					}
				} else {
					log.info("System setting does not require question answer, just send the password to the user");
					emailPasswordToUser(actionData, email);
					forward = "success";
				}
			} else if  (actionData.wasButtonPressed("hint.answer.given")) {
				if (userManager.isHintAnswerIsCorrect(ThreadProperties.getDomain(), form.getEmailAddress(), form.getAnswer())) {
					forward = "success";
					emailPasswordToUser(actionData, email);
				} else {
					throw new SystemException("Hint answer is incorrect - this problem should be discovered by validation");
				}
			} else if ((email == null) || (email.trim().length() == 0)) {
				forward = "need.email.address";
			}
		}
		log.info("At end of execute - Prefix  = " + actionData.getMapping().getPrefix());
		log.info("At end of execute - Path    = " + actionData.getMapping().getPath());
		log.info("At end of execute - Forward = " + forward);
		return(forward);
	}

	
	
	private void emailPasswordToUser(VectricsActionData actionData, String emailAddress) {
		Domain domain = ThreadProperties.getDomain();
		String body = "";
		Person person = userManager.findPersonWithEMail(domain, emailAddress);
		PasswordEncryptor encryptor = new PasswordEncryptor();

		log.debug("Account found, e-mail password");
        body = "Account Information for Sign-In for " 
        		+ RecruitConfig.getRecruitInstance().getCompanyName(domain)
        		+ "\r\n\r\n";
        		
        String password = person.getUser().getPassword();
        log.info("Encrypted password = " + password);
        String decryptedPassword = password;
        if (person.getUser().getPasswordEncrypted())
        		decryptedPassword = encryptor.decrypt(password);
		body += "\r\nUser Name: " + person.getUser().getUserName() + "\r\n\r\n";	        	
		body +=     "Password:  " + decryptedPassword + "\r\n";
		body += "\r\n\r\n";	        	

		log.info("Sending password email to person: " + person + "   Email: " + person.getContactInfo().getEmail());
		MailMessage mailMessage = new MailMessage(domain);
		mailMessage.setBody(body);
		mailMessage.setSubject(this.getPhrase("email.subject.account.information", actionData.getLocale()));
		mailMessage.setContentType(MailMessage.CONTENT_TEXT);
		mailMessage.setFromAddress(CoreServiceLocator.getConfiguration().getFromMailConfiguration(domain).getMailUserName());
		mailMessage.setFromName(CoreServiceLocator.getConfiguration().getFromMailConfiguration(domain).getMailUserName());
		
		UserMailer userMailer = new UserMailer(CoreServiceLocator.getConfiguration().getFromMailConfiguration(domain));
		userMailer.sendMessage(person, mailMessage);
	}

}